package cn.mazd.imagestorage.controller;

import cn.mazd.imagestorage.bean.ResultBean;
import cn.mazd.imagestorage.util.UploadUtil;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import lombok.extern.slf4j.Slf4j;


@Slf4j
@RestController
public class UploadController {
    private final UploadUtil uploadUtil;

    @Value("${fingerling.upload.image.accessKeyId}")
    private String accessKeyId;


    @Value("${fingerling.upload.image.accessKeySecret}")
    private String accessKeySecret;


    public UploadController(UploadUtil uploadUtil) {
        this.uploadUtil = uploadUtil;
    }

    @PostMapping("/upload")
    public ResultBean uploadFile(@RequestParam("fileData")String fileData,
                                 @RequestHeader("accessKeyId") String key, @RequestHeader("accessKeySecret") String secret){
        if(key == null && secret == null){
            return new ResultBean(01,"非法请求",null);
        }else if(!accessKeyId.equals(key) || !accessKeySecret.equals(secret)){
            return new ResultBean(02,"令牌鉴权失败",null);
        }
        log.info("request:{}",fileData);
        String img = null;
        MultipartFile file = uploadUtil.base64ToMultipart(fileData);
        try {
            img = uploadUtil.upload(file);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultBean(03,"上传失败",null);
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("url",img);
        return new ResultBean(0,"成功",jsonObject);
    }



    @PostMapping("/uploadfile")
    public ResultBean uploadFile(@RequestParam("fileData")MultipartFile fileData, @RequestHeader String key, @RequestHeader String secret){
        if(key == null && secret == null){
            return new ResultBean(01,"非法请求",null);
        }else if(!accessKeyId.equals(key) || !accessKeySecret.equals(secret)){
            return new ResultBean(02,"令牌鉴权失败",null);
        }
        log.info("request:{}",fileData);
        String img = null;
//        MultipartFile file = uploadUtil.base64ToMultipart(fileData);
        MultipartFile file = fileData;
        try {
            img = uploadUtil.upload(file);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultBean(03,"上传失败",null);
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("url",img);
        return new ResultBean(0,"成功",jsonObject);
    }


}
